package edu.ruc.cluster.action;

import java.io.IOException;
import java.util.Map;
import java.util.HashMap;

import edu.ruc.cluster.util.AbstractInteractiveCommand;

/**
 * 2012-12-4 
 * This class shows how to add and delete a user in a remote machine. It extends the AbstractInteractiveCommand
 * Need to fill Properties property before call dealCmd command
 * @author deke
 *
 */
public class UserAddCmd extends AbstractInteractiveCommand {

	public UserAddCmd(String host, String passwd){
		super(host, passwd);
	}
	@Override
	public void interactProcess(String cmd){
		// TODO Auto-generated method stub
//		String host = getHost();
		String[] commands = cmd.split("xxx");
		try{
			int count = 1;
			for(int i = 0 ; i < commands.length ; i ++){
				writor.write((commands[i] + "\n").getBytes());
				writor.flush();
		    	
		    	char[] cbuf = new char[1024];			
				int ret = reader.read(cbuf);
				
				while(ret != -1){
					String info = new String(cbuf, 0, ret);
					System.out.print(info);
					if(info.contains("[sudo] ")){
						writor.write((getPasswd() + "\n").getBytes());
				    	writor.flush();
					}
					else if(info.contains("Retype")){
						writor.write((property.getProperty("passwd")+"\n").getBytes());
						writor.flush();
					}else if(info.contains("New UNIX password")){
						writor.write((property.getProperty("passwd")+"\n").getBytes());
						writor.flush();
					}else if(info.contains("[" + getUser()+ "@")){						
						if(count == 0){
	//						System.out.println(i + "break");
							break;
						}
						count --;
					}
					
					ret = reader.read(cbuf);
				}
			}
	    	
		}catch(IOException e){
			logHandler.error(this.getClass().getSimpleName() + e.getMessage(), e);
		}
	}
	public void adduser(String username, String passwd){
		Map<String, String> info = new HashMap<String, String>();
		info.put("username", username);
		info.put("passwd", passwd);
		setProperty(info);
		String addusercmd = "sudo /usr/sbin/adduser " + username + " -d /home/" + username;
		String passwdcmd = "sudo passwd " + username;
		dealcmd(addusercmd + "xxx" + passwdcmd);
	}
	public void deluser(String username){
		String cmd = "sudo /usr/sbin/userdel -r " + username;		
		dealcmd(cmd);
	}
	public static void main(String[] args){		
		
		// the host and passwd if used for ssh, which means the user is add on the machine "host" indicates
		String host = "deke@dlnode26";
		String passwd = "111111";
		UserAddCmd ha = new UserAddCmd(host, passwd);	
		
		// the username and password is used for user to be added 
		String addusername = "abc";
		String adduserpw = "123456";		
		ha.adduser(addusername, adduserpw);
//		ha.deluser(addusername);
		
	}

}
